package com.shyroke.daydayzhuanweb.controller;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.dto.LayEditRespon;
import com.shyroke.daydayzhuanapi.dto.BusinessRequest;
import com.shyroke.daydayzhuanapi.entity.BusinessEntity;
import com.shyroke.daydayzhuanapi.entity.QBusinessEntity;
import com.shyroke.daydayzhuandao.respository.BusinessRepository;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.util.ExceptionUtil;
import com.shyroke.daydayzhuansvc.util.OSSClientConstants;
import com.shyroke.daydayzhuansvc.util.PermissionAnnotation;
import com.shyroke.daydayzhuansvc.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * 类名 ：商务合作controller
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/11 10:46
 */
@Controller
@RequestMapping(value = "admin/business")
public class BusinessController extends  BaseController{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private IOSSService ossService;

    @RequestMapping(value = "desc")
    public ModelAndView desc(ModelAndView model){
        QBusinessEntity qBusinessEntity = QBusinessEntity.businessEntity;
        List<BusinessEntity> list = factory.selectFrom(qBusinessEntity).limit(1).fetch();
        model.addObject("business", CollectionUtils.isEmpty(list)?null:list.get(0));
        model.setViewName("admin/business/desc");
        return model;

    }


    /**
     * 保存商务合作内容的图片
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadBusinessImg")
    @ResponseBody
    public LayEditRespon uploadProjectImg(MultipartFile file){
        LayEditRespon respon = new LayEditRespon();

        if(file.isEmpty()){
            respon.setCode(-1);
            respon.setMsg("图片为空");
            return respon;
        }

        String path = OSSClientConstants.BUSINESS_PATH+file.getOriginalFilename();
        String url;
        try {
            ossService.uploadImg(file,path);
            url = ossService.getImgUrl(path);
            //加水印
            url = url + OSSClientConstants.WATER_MARK;
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            respon.setCode(-1);
            respon.setMsg("图片上传失败");
            return respon;
        }

        Map<String,Object> data = new HashMap<String,Object>();

        data.put("src",url);

        respon.setCode(0);
        respon.setMsg("保存成功");
        respon.setData(data);

        return respon;
    }


    /**
     * 修改商务合作
     * @param business
     * @return
     */
    @PermissionAnnotation(permissionName = "business:update")
    @RequestMapping(value = "update")
    @ResponseBody
    public R free_project_update(@RequestBody BusinessRequest business, HttpSession session){

        //防止图片地址的字符被转义，比如a(1).png会被转义成a%281%29.png,导致显示错误。
        try {
            if(business.getContent()!=null){
                business.setContent(URLDecoder.decode(business.getContent(),"utf-8"));
            }
        }catch (Exception e){
            logger.info("转义失败，原因="+ExceptionUtil.getMessage(e));
            return R.error("转义失败");
        }
        Optional<BusinessEntity> optionalBusinessEntity = businessRepository.findById(business.getId());
        if (optionalBusinessEntity.isPresent()) {
            BusinessEntity businessEntity = optionalBusinessEntity.get();
            businessEntity.setContent(business.getContent());
            businessRepository.save(businessEntity);
        }
        return R.ok("修改成功！");
    }

}
